<?php

namespace Phones\MainBundle\Entity;

use Doctrine\ORM\EntityRepository;

class Repository extends EntityRepository {

    const ITEMS_PER_PAGE = 10;

    public function find($options = array()) {
        $entityName = $this->getEntity();

        // select
        if (empty($options['fields'])) {
            $options['fields'] = $entityName;
        }

        // where
        if (empty($options['conditions'])) {
            $options['conditions'] = array();
        }

        // order by
        if (empty($options['order'])) {
            $options['order'] = "{$entityName}.id";
        }

        $sql = 'SELECT ' . $options['fields'] . ' '
              .'FROM PhonesMainBundle:' . $entityName . ' ' . $entityName . ' '
              . $this->parseConditions($options['conditions']) . ' '
              .'ORDER BY ' . $options['order'];

        return $this->getEntityManager()
                    ->createQuery($sql)
                    ->getResult();
    }

    private function getEntity() {
        $ns = explode("\\", $this->getClassName());
        return end($ns);
    }

    private function parseConditions($conditions) {
        $sql = '';
        if (! empty($conditions)) {
            $sql .= "WHERE ";
            foreach ($conditions as $k=>$v) {
                $sql .= "{$k} = {$v} AND";
            }
            $sql = preg_replace('/\s+and+\s*$/i', '', $sql);
        }

        return $sql;
    }
}